import wxValidate from 'wechat-validate'
import Dialog from '@vant/weapp/dialog/index'
Page({
  behaviors: [wxValidate],
  data: {
    currentDate: new Date().getTime(),
    houseLayerVisible: false,
    repairLayerVisible: false,
    dateLayerVisible: false,
    mobile:'',//手机
    appointment:'',//预约日期
    description:'',//问题描述
    houseId:'',//选中房屋id
    houseName:'',
    repairItemId:'',//报修id
    repairItemName:'',//维修得类别名
    houseList: [
      /* { name: '北京西三旗花园1号楼 101' },
      { name: '北京东村家园3号楼 302' },
      { name: '北京育新花园3号楼 703' },
      { name: '北京天通苑北苑8号楼 403' }, */
    ],
    repairItem: [/* { name: '水路卫浴' }, { name: '电路灯具' }, { name: '管道疏通' }, { name: '开锁换锁' } */],
    attachment: [
      /* { url: '/repair_pkg/static/uploads/attachment.jpg' },
      { url: '/repair_pkg/static/uploads/attachment.jpg' }, */
    ],
  },
  rules: {
    houseId: [
      {required: true, message: '请选择报修房屋!'}
    ],
    repairItemId: [
      {required: true, message: '请选择维修的项目!'}
    ],
    mobile: [
      {required: true, message: '请填写手机号码!'},
      {pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!'},
    ],
    appointment: [
      {required: true, message: '请选择预约日期!'}
    ],
    description: [
      {required: true, message: '请填写问题描述!'}
    ],
  },
  async onLoad() {
    if (this.options.id) {
      // 有id，修改
      const res = await wx.http({ url: '/repair/' + this.options.id })
      this.setData({ ...res.data, houseName: res.data.houseInfo })
    }
  },
  setAppointment(e){
    this.setData({
      appointment:wx.utils.formatTimestampToString(e.detail),
      dateLayerVisible:false
    })
  },
 /*  // 获取维修项目
  async getRepairItem() {
    // 调用接口
    const { code, data: repairItem } = await wx.http.get('/repairItem')
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    // 渲染数据
    this.setData({ repairItem })
  },
    // 获取房屋列表（必须是通过审核的房屋）
  async getHouseList() {
      // 调用接口
      const { code, data: houseList } = await wx.http.get('/house')
      // 检测接口是否调用成功
      if (code !== 10000) return wx.utils.toast()
      // 渲染数据
      this.setData({ houseList })
    }, */
    // 获用户选择的房屋
  selectHouseInfo(ev) {
    // 数据渲染
    this.setData({
      houseId: ev.detail.id,
      houseName: ev.detail.name,
    })
  },
  // 获取用户选择的维修项目
  selectRepairItemInfo(ev) {
    this.setData({
      repairItemId: ev.detail.id,
      repairItemName: ev.detail.name,
    })
  },
  async openHouseLayer() {
      // 获取我的房屋列表
    const res = await wx.http({ url: '/room' })
    this.setData({
      houseList: res.data.map((v) => ({
        id: v.id,
        name: v.point + v.building + v.room,
      })),
      houseLayerVisible: true
     })
    /* // 调用接口
    const res = await wx.http({url:'/room'})
    // 渲染数据
    this.setData({ 
      houseList:res.data.map((v)=>({
        id:v.id,
        name:v.point+v.building+v.room
      })),
      houseLayerVisible:true 
    }) */
  },
  
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  async openRepairLayer() {
    const res = await wx.http({ url: '/repairItem' })
    this.setData({
      repairItem:res.data,
      repairLayerVisible: true
    })
  },
  closeRepairLayer() {
    this.setData({
      repairLayerVisible: false,
    })
  },

  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  /* goList() {
    wx.reLaunch({
      url: '/repair_pkg/pages/list/index',
    })
  }, */
  // 上传文件
  async afterRead(ev) {
    const promises =ev.detail.file.map((v)=> wx.http.uploadFile(v.tempFilePath,false,false))
      const result = await Promise.allSettled(promises)
      
      // 手动来关闭loading
      wx.hideLoading()

      //给每个结果添加一个index属性，目的是为了知道第几张图片上传报错
      result.forEach((v,i)=>(v.index=i))

      const successResults = result.filter((v)=>v.status==='fulfilled')
      const failResults = result.filter((v)=>v.status==='rejected')

      this.setData({
        attachment:[...this.data.attachment,...successResults.map((v)=>v.value.data)]
      })
      //如果有上传失败的，提示第几张
      if(failResults.length>0){
        //提高用户体验，弹出一个确认框
        Dialog.alert({
          /* message:`第${failResults.map((v)=>v.index+1).join('、')}张上传失败` */
          title: '上传失败',
          message: failResults
          .map((v) => {
            const { message } = JSON.parse(v.reason.data)
            return `第${v.index + 1}张：${message}`
          })
          .join('\r\n'),
        })
      }
    /* // 上传文件的信息
    const { file } = ev.detail
    // 调用 API 实现文件上传
    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: file.url,
      name: 'file',
      header: {
        Authorization: 'Bearer ' + getApp().token,
      },
      success: (result) => {
        // 处理返回的 json 数据
        const data = JSON.parse(result.data)
        // 检测接口是否调用成功
        if (data.code !== 10000) return wx.utils.toast('文件上传失败!')
        // 先获取原来已经上传的图片
        const { attachment } = this.data
        // 追加新的上传的图片
        attachment.push(data.data)
        // 渲染数据
        this.setData({ attachment })
      }, */ 
  },
  delete(e){
    console.log(e,'event');
    let list = this.data.attachment
    list.splice(e.detail.index,1)
    this.setData({
      attachment:list
    })
  },
  async submitForm() {
        // 验证表单数据
        if (!this.validate()) return
        // 提取接口需要的数据
        const {houseId, repairItemId, mobile, appointment, description, attachment} = this.data
        const formData = {houseId, repairItemId, mobile, appointment, description, attachment}
        
        if (this.options.id) {
          formData.id = this.options.id
        }

        const res = await wx.http({
          method:'post',
          url:'/repair',
          data:formData
        })
        /* // 调用接口
        const {code} = await wx.http.post('/repair', {
          houseId,
          repairItemId,
          mobile,
          appointment,
          description,
          attachment,
        })
        // 检测接口是否调用成功
        if (code !== 10000) return wx.utils.toast('在线报修失败!') */
        if(this.options.id){
          //到这行说明修改
          //1、获取页面栈
          const pages = getCurrentPages()
          //取到list页面实例
          const listPage = pages.find((v)=>v.route==='repair_pkg/pages/list/index')
          //3、调用list页面实例的 updateRepairItem方法更新数据
          listPage.updateRepairItem({
            ...formData,
            houseInfo:this.data.houseName,
            repairItemName:this.data.repairItemName,
            status:this.data.status
          })
          wx.navigateBack()
        }else{
          //1、获取页面栈
          const pages = getCurrentPages()
          const prevPage = pages[pages.length -2]

          //如果上一个页面是列表页，直接后退一步
          if(prevPage.route === 'repair_pkg/pages/list/index'){
            // 如果能够进入这个if判断，说明prevPage是什么页面实例？list页面实例

            prevPage.addRepairItemToListTop({
            ...formData,
            houseInfo: this.data.houseName,
            repairItemName: this.data.repairItemName,
            status: 1, // 新添加的报修信息，状态默认为：1-受理中
            id: res.data.id,
          })
            wx.navigateBack()
          }else{
            // 跳转到报修列表页面
            wx.redirectTo({
              url: '/repair_pkg/pages/list/index',
             })
          }
          
        }
      },
})
